﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Client;
using System.Threading.Tasks;
using System.Diagnostics;
using PServiceBus.Services.Gateway.Runtime;

namespace ChatApp {

    class Program {
        static string _userName = string.Empty;
        static void Main(string[] args) {

            ESB.ReThrowException(true);

            Console.WriteLine("Please enter your username: ");
            _userName = Console.ReadLine().Replace(" ", "_").Replace("\r\n", "").Replace("\n", "");

            PSBClient.OnDisconnect = () => SendMessage("remove-user");

            PSBClient.Subscribe<ChatTopic>(msg =>
            {
                if (msg.Message == null) return;
                if (msg.Message == "add-user") {
                    Console.WriteLine("{0} has joined the chat room\n", msg.UserName);
                } else if (msg.Message == "remove-user") {
                    Console.WriteLine("{0} has left the chat room\n", msg.UserName);
                } else if (msg.Message != null && msg.Message.Contains("start-chat|")) {
                    //TODO nothing for now
                } else Console.WriteLine("{0}: {1}\n", msg.UserName, msg.Message);

            }, filter: String.Format("UserName != {0}", _userName));

            SendMessage("add-user");
            
            Console.WriteLine("Type exit to end chat. You can start typing your message");
            
            
            while (true) {
                var text = Console.ReadLine();
                if (text.ToLower() == "exit") {
                    break;
                }
                else if (text.ToLower() == "get-all") {
                    PSBClient.Update<ChatTopic>();
                } else if (text.ToLower() == "only-mine") {
                    PSBClient.Update<ChatTopic>(String.Format("UserName != {0}", _userName));
                } else {
                    SendMessage(text);
                    Console.WriteLine("You: {0}\n", text);
                }
            }
        }

        static void SendMessage(string message) {
            PSBClient.Publish(ChatTopic.New(_userName, message));
        }

    }

    public class ChatTopic {
        public string UserName { get; set; }
        public string Message { get; set; }
        public static ChatTopic New(string username, string message) {
            return new ChatTopic { UserName = username, Message = message };
        }
    }
}
